package com.qxsx.midi.utils;




import android.util.Base64;
import android.util.Log;

import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;

/**
 * Created by gong on 2015/7/23.
 */
public class AesEncode {

    static String keyStr = "1234567812345678";
    static String ivStr = "1234567812345678";


    public static String string2md5(String data) {
        try {
            byte[] btInput = data.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(btInput);
            byte[] md = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < md.length; i++) {
                int val = md[i]&0xff;
                if (val < 16)
                    sb.append("0");
                sb.append(Integer.toHexString(val));
            }
            Log.i("111111 md5:",sb.toString());
            return sb.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public static String encrypt( String strIn) throws Exception {
        while(strIn.getBytes("utf-8").length %16 != 0)
            strIn = strIn + '\n';
        SecretKeySpec skeySpec = getKey(keyStr);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(strIn.getBytes("utf-8"));

        return new String(Base64.encode(encrypted,Base64.DEFAULT));
//        return new BASE64Encoder().encode(encrypted);
    }

    public static String decrypt( String strIn) throws Exception {
        SecretKeySpec skeySpec = getKey(keyStr);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
//        byte[] encrypted1 = new BASE64Decoder().decodeBuffer(strIn);
        byte[] encrypted1 = Base64.decode(strIn,Base64.DEFAULT);

        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original,"utf-8");
        return originalString;
    }

    private static SecretKeySpec getKey(String strKey) throws Exception {
        byte[] arrBTmp = strKey.getBytes();
        byte[] arrB = new byte[16]; // 创建一个空的16位字节数组（默认值为0）

        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }

        SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");

        return skeySpec;
    }

}
